<template>
    <FormDrawer ref="formDawerRef" title="推荐商品" @submit="handleContent" confirmText="关联">
        <el-table :data="tableData" border stripe style="width: 100%">
            <el-table-column prop="goods_id" width="60" label="ID"></el-table-column>
            <el-table-column width="180" label="商品封面">
                <template #default="{ row }">
                    <el-image :src="row.cover" fit="fill" :lazy="true" style="width: 64px; height: 64px;"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="name" width="180" label="商品名称"></el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-popconfirm title="是否删除该记录" confirmButtonText="确认" cancelButtonText="取消"
                        @confirm.stop="handleDelete(row)">
                        <template #reference>
                            <el-button type="primary" text size="small" :loading="row.loading">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
    </FormDrawer>

    <ChooseGoods ref="ChooseGoodsRef"></ChooseGoods>
</template>
<script setup>
import { ref } from 'vue'
import {
    getGoodsList
} from '@/api/goods.js'
import FormDrawer from '@/components/FormDrawer.vue'
import { elNotification } from '@/hooks/elNotification.js'
import ChooseGoods from '@/components/ChooseGoods.vue'

import {
    getCateGoryGoods,
    deleteCategoryGoods,
    connectCategoryGoods
} from '@/api/category.js'


const formDawerRef = ref(null)
const category_id = ref(0)
const tableData = ref([])

const open = (item) => {
    category_id.value = item.id
    item.goodsDrawerLoading = true
    getData().then(() => formDawerRef.value.open()).finally(() => {
        item.goodsDrawerLoading = false
    })

}

function getData() {
    return getCateGoryGoods(category_id.value).then(res => {
        tableData.value = res.map(o => {
            o.loading = false
            return o
        })
    })
}

const handleDelete = (row) => {
    row.loading = true
    deleteCategoryGoods(row.id).then(res => {
        elNotification("删除成功")
        getData()
    }).finally(() => {
        row.loading = false
    })
}

const ChooseGoodsRef = ref(null)
const handleContent = () => {
    ChooseGoodsRef.value.open((goods_ids) => {
        formDawerRef.value.showLoading()
        connectCategoryGoods({
            category_id: category_id.value,
            goods_ids
        }).then((res) => {
            getData()
            elNotification("关联成功")
        }).finally(() => {
            formDawerRef.value.hideLoading()
        })
    })
}

defineExpose({
    open
})
</script>
<style scoped lang="less"></style>
